home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / inspect.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  36.2 KB  |  1,017 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Get useful information from live Python objects.
  5.  
  6. This module encapsulates the interface provided by the internal special
  7. attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
  8. It also provides some help for examining source code and class layout.
  9.  
  10. Here are some of the useful functions provided by this module:
  11.  
  12.     ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
  13.         isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
  14.         isroutine() - check object types
  15.     getmembers() - get members of an object that satisfy a given condition
  16.  
  17.     getfile(), getsourcefile(), getsource() - find an object's source code
  18.     getdoc(), getcomments() - get documentation on an object
  19.     getmodule() - determine the module that an object came from
  20.     getclasstree() - arrange classes so as to represent their hierarchy
  21.  
  22.     getargspec(), getargvalues() - get info about function arguments
  23.     formatargspec(), formatargvalues() - format an argument spec
  24.     getouterframes(), getinnerframes() - get info about frames
  25.     currentframe() - get the current stack frame
  26.     stack(), trace() - get info about frames on the stack or in a traceback
  27. """
  28. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  29. __date__ = '1 Jan 2001'
  30. import sys
  31. import os
  32. import types
  33. import string
  34. import re
  35. import dis
  36. import imp
  37. import tokenize
  38. import linecache
  39. from operator import attrgetter
  40. from collections import namedtuple
  41. (CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS) = (1, 2, 4, 8)
  42. (CO_NESTED, CO_GENERATOR, CO_NOFREE) = (16, 32, 64)
  43. TPFLAGS_IS_ABSTRACT = 1048576
  44.  
  45. def ismodule(object):
  46.     '''Return true if the object is a module.
  47.  
  48.     Module objects provide these attributes:
  49.         __doc__         documentation string
  50.         __file__        filename (missing for built-in modules)'''
  51.     return isinstance(object, types.ModuleType)
  52.  
  53.  
  54. def isclass(object):
  55.     '''Return true if the object is a class.
  56.  
  57.     Class objects provide these attributes:
  58.         __doc__         documentation string
  59.         __module__      name of module in which this class was defined'''
  60.     if not isinstance(object, types.ClassType):
  61.         pass
  62.     return hasattr(object, '__bases__')
  63.  
  64.  
  65. def ismethod(object):
  66.     '''Return true if the object is an instance method.
  67.  
  68.     Instance method objects provide these attributes:
  69.         __doc__         documentation string
  70.         __name__        name with which this method was defined
  71.         im_class        class object in which this method belongs
  72.         im_func         function object containing implementation of method
  73.         im_self         instance to which this method is bound, or None'''
  74.     return isinstance(object, types.MethodType)
  75.  
  76.  
  77. def ismethoddescriptor(object):
  78.     '''Return true if the object is a method descriptor.
  79.  
  80.     But not if ismethod() or isclass() or isfunction() are true.
  81.  
  82.     This is new in Python 2.2, and, for example, is true of int.__add__.
  83.     An object passing this test has a __get__ attribute but not a __set__
  84.     attribute, but beyond that the set of attributes varies.  __name__ is
  85.     usually sensible, and __doc__ often is.
  86.  
  87.     Methods implemented via descriptors that also pass one of the other
  88.     tests return false from the ismethoddescriptor() test, simply because
  89.     the other tests promise more -- you can, e.g., count on having the
  90.     im_func attribute (etc) when an object passes ismethod().'''
  91.     if hasattr(object, '__get__') and not hasattr(object, '__set__') and not ismethod(object) and not isfunction(object):
  92.         pass
  93.     return not isclass(object)
  94.  
  95.  
  96. def isdatadescriptor(object):
  97.     '''Return true if the object is a data descriptor.
  98.  
  99.     Data descriptors have both a __get__ and a __set__ attribute.  Examples are
  100.     properties (defined in Python) and getsets and members (defined in C).
  101.     Typically, data descriptors will also have __name__ and __doc__ attributes
  102.     (properties, getsets, and members have both of these attributes), but this
  103.     is not guaranteed.'''
  104.     if hasattr(object, '__set__'):
  105.         pass
  106.     return hasattr(object, '__get__')
  107.  
  108. if hasattr(types, 'MemberDescriptorType'):
  109.     
  110.     def ismemberdescriptor(object):
  111.         '''Return true if the object is a member descriptor.
  112.  
  113.         Member descriptors are specialized descriptors defined in extension
  114.         modules.'''
  115.         return isinstance(object, types.MemberDescriptorType)
  116.  
  117. else:
  118.     
  119.     def ismemberdescriptor(object):
  120.         '''Return true if the object is a member descriptor.
  121.  
  122.         Member descriptors are specialized descriptors defined in extension
  123.         modules.'''
  124.         return False
  125.  
  126. if hasattr(types, 'GetSetDescriptorType'):
  127.     
  128.     def isgetsetdescriptor(object):
  129.         '''Return true if the object is a getset descriptor.
  130.  
  131.         getset descriptors are specialized descriptors defined in extension
  132.         modules.'''
  133.         return isinstance(object, types.GetSetDescriptorType)
  134.  
  135. else:
  136.     
  137.     def isgetsetdescriptor(object):
  138.         '''Return true if the object is a getset descriptor.
  139.  
  140.         getset descriptors are specialized descriptors defined in extension
  141.         modules.'''
  142.         return False
  143.  
  144.  
  145. def isfunction(object):
  146.     '''Return true if the object is a user-defined function.
  147.  
  148.     Function objects provide these attributes:
  149.         __doc__         documentation string
  150.         __name__        name with which this function was defined
  151.         func_code       code object containing compiled function bytecode
  152.         func_defaults   tuple of any default values for arguments
  153.         func_doc        (same as __doc__)
  154.         func_globals    global namespace in which this function was defined
  155.         func_name       (same as __name__)'''
  156.     return isinstance(object, types.FunctionType)
  157.  
  158.  
  159. def isgeneratorfunction(object):
  160.     '''Return true if the object is a user-defined generator function.
  161.  
  162.     Generator function objects provides same attributes as functions.
  163.  
  164.     See isfunction.__doc__ for attributes listing.'''
  165.     if isfunction(object) or ismethod(object):
  166.         pass
  167.     return bool(object.func_code.co_flags & CO_GENERATOR)
  168.  
  169.  
  170. def isgenerator(object):
  171.     '''Return true if the object is a generator.
  172.  
  173.     Generator objects provide these attributes:
  174.         __iter__        defined to support interation over container
  175.         close           raises a new GeneratorExit exception inside the
  176.                         generator to terminate the iteration
  177.         gi_code         code object
  178.         gi_frame        frame object or possibly None once the generator has
  179.                         been exhausted
  180.         gi_running      set to 1 when generator is executing, 0 otherwise
  181.         next            return the next item from the container
  182.         send            resumes the generator and "sends" a value that becomes
  183.                         the result of the current yield-expression
  184.         throw           used to raise an exception inside the generator'''
  185.     return isinstance(object, types.GeneratorType)
  186.  
  187.  
  188. def istraceback(object):
  189.     '''Return true if the object is a traceback.
  190.  
  191.     Traceback objects provide these attributes:
  192.         tb_frame        frame object at this level
  193.         tb_lasti        index of last attempted instruction in bytecode
  194.         tb_lineno       current line number in Python source code
  195.         tb_next         next inner traceback object (called by this level)'''
  196.     return isinstance(object, types.TracebackType)
  197.  
  198.  
  199. def isframe(object):
  200.     """Return true if the object is a frame object.
  201.  
  202.     Frame objects provide these attributes:
  203.         f_back          next outer frame object (this frame's caller)
  204.         f_builtins      built-in namespace seen by this frame
  205.         f_code          code object being executed in this frame
  206.         f_exc_traceback traceback if raised in this frame, or None
  207.         f_exc_type      exception type if raised in this frame, or None
  208.         f_exc_value     exception value if raised in this frame, or None
  209.         f_globals       global namespace seen by this frame
  210.         f_lasti         index of last attempted instruction in bytecode
  211.         f_lineno        current line number in Python source code
  212.         f_locals        local namespace seen by this frame
  213.         f_restricted    0 or 1 if frame is in restricted execution mode
  214.         f_trace         tracing function for this frame, or None"""
  215.     return isinstance(object, types.FrameType)
  216.  
  217.  
  218. def iscode(object):
  219.     '''Return true if the object is a code object.
  220.  
  221.     Code objects provide these attributes:
  222.         co_argcount     number of arguments (not including * or ** args)
  223.         co_code         string of raw compiled bytecode
  224.         co_consts       tuple of constants used in the bytecode
  225.         co_filename     name of file in which this code object was created
  226.         co_firstlineno  number of first line in Python source code
  227.         co_flags        bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  228.         co_lnotab       encoded mapping of line numbers to bytecode indices
  229.         co_name         name with which this code object was defined
  230.         co_names        tuple of names of local variables
  231.         co_nlocals      number of local variables
  232.         co_stacksize    virtual machine stack space required
  233.         co_varnames     tuple of names of arguments and local variables'''
  234.     return isinstance(object, types.CodeType)
  235.  
  236.  
  237. def isbuiltin(object):
  238.     '''Return true if the object is a built-in function or method.
  239.  
  240.     Built-in functions and methods provide these attributes:
  241.         __doc__         documentation string
  242.         __name__        original name of this function or method
  243.         __self__        instance to which a method is bound, or None'''
  244.     return isinstance(object, types.BuiltinFunctionType)
  245.  
  246.  
  247. def isroutine(object):
  248.     '''Return true if the object is any kind of function or method.'''
  249.     if not isbuiltin(object) and isfunction(object) and ismethod(object):
  250.         pass
  251.     return ismethoddescriptor(object)
  252.  
  253.  
  254. def isgenerator(object):
  255.     '''Return true if the object is a generator object.'''
  256.     return isinstance(object, types.GeneratorType)
  257.  
  258.  
  259. def isabstract(object):
  260.     '''Return true if the object is an abstract base class (ABC).'''
  261.     if isinstance(object, type):
  262.         pass
  263.     return object.__flags__ & TPFLAGS_IS_ABSTRACT
  264.  
  265.  
  266. def getmembers(object, predicate = None):
  267.     '''Return all members of an object as (name, value) pairs sorted by name.
  268.     Optionally, only return members that satisfy a given predicate.'''
  269.     results = []
  270.     for key in dir(object):
  271.         value = getattr(object, key)
  272.         if not predicate or predicate(value):
  273.             results.append((key, value))
  274.             continue
  275.     
  276.     results.sort()
  277.     return results
  278.  
  279. Attribute = namedtuple('Attribute', 'name kind defining_class object')
  280.  
  281. def classify_class_attrs(cls):
  282.     """Return list of attribute-descriptor tuples.
  283.  
  284.     For each name in dir(cls), the return list contains a 4-tuple
  285.     with these elements:
  286.  
  287.         0. The name (a string).
  288.  
  289.         1. The kind of attribute this is, one of these strings:
  290.                'class method'    created via classmethod()
  291.                'static method'   created via staticmethod()
  292.                'property'        created via property()
  293.                'method'          any other flavor of method
  294.                'data'            not a method
  295.  
  296.         2. The class which defined this attribute (a class).
  297.  
  298.         3. The object as obtained directly from the defining class's
  299.            __dict__, not via getattr.  This is especially important for
  300.            data attributes:  C.data is just a data object, but
  301.            C.__dict__['data'] may be a data descriptor with additional
  302.            info, like a __doc__ string.
  303.     """
  304.     mro = getmro(cls)
  305.     names = dir(cls)
  306.     result = []
  307.     for name in names:
  308.         if name in cls.__dict__:
  309.             obj = cls.__dict__[name]
  310.         else:
  311.             obj = getattr(cls, name)
  312.         homecls = getattr(obj, '__objclass__', None)
  313.         if homecls is None:
  314.             for base in mro:
  315.                 if name in base.__dict__:
  316.                     homecls = base
  317.                     break
  318.                     continue
  319.             
  320.         
  321.         if homecls is not None and name in homecls.__dict__:
  322.             obj = homecls.__dict__[name]
  323.         
  324.         obj_via_getattr = getattr(cls, name)
  325.         if isinstance(obj, staticmethod):
  326.             kind = 'static method'
  327.         elif isinstance(obj, classmethod):
  328.             kind = 'class method'
  329.         elif isinstance(obj, property):
  330.             kind = 'property'
  331.         elif ismethod(obj_via_getattr) or ismethoddescriptor(obj_via_getattr):
  332.             kind = 'method'
  333.         else:
  334.             kind = 'data'
  335.         result.append(Attribute(name, kind, homecls, obj))
  336.     
  337.     return result
  338.  
  339.  
  340. def _searchbases(cls, accum):
  341.     if cls in accum:
  342.         return None
  343.     accum.append(cls)
  344.     for base in cls.__bases__:
  345.         _searchbases(base, accum)
  346.     
  347.  
  348.  
  349. def getmro(cls):
  350.     '''Return tuple of base classes (including cls) in method resolution order.'''
  351.     if hasattr(cls, '__mro__'):
  352.         return cls.__mro__
  353.     result = []
  354.     _searchbases(cls, result)
  355.     return tuple(result)
  356.  
  357.  
  358. def indentsize(line):
  359.     '''Return the indent size, in spaces, at the start of a line of text.'''
  360.     expline = string.expandtabs(line)
  361.     return len(expline) - len(string.lstrip(expline))
  362.  
  363.  
  364. def getdoc(object):
  365.     '''Get the documentation string for an object.
  366.  
  367.     All tabs are expanded to spaces.  To clean up docstrings that are
  368.     indented to line up with blocks of code, any whitespace than can be
  369.     uniformly removed from the second line onwards is removed.'''
  370.     
  371.     try:
  372.         doc = object.__doc__
  373.     except AttributeError:
  374.         return None
  375.  
  376.     if not isinstance(doc, types.StringTypes):
  377.         return None
  378.     return cleandoc(doc)
  379.  
  380.  
  381. def cleandoc(doc):
  382.     '''Clean up indentation from docstrings.
  383.  
  384.     Any whitespace that can be uniformly removed from the second line
  385.     onwards is removed.'''
  386.     
  387.     try:
  388.         lines = string.split(string.expandtabs(doc), '\n')
  389.     except UnicodeError:
  390.         return None
  391.  
  392.     margin = sys.maxint
  393.     for line in lines[1:]:
  394.         content = len(string.lstrip(line))
  395.         if content:
  396.             indent = len(line) - content
  397.             margin = min(margin, indent)
  398.             continue
  399.     
  400.     if lines:
  401.         lines[0] = lines[0].lstrip()
  402.     
  403.     if margin < sys.maxint:
  404.         for i in range(1, len(lines)):
  405.             lines[i] = lines[i][margin:]
  406.         
  407.     
  408.     while lines and not lines[-1]:
  409.         lines.pop()
  410.     while lines and not lines[0]:
  411.         lines.pop(0)
  412.     return string.join(lines, '\n')
  413.  
  414.  
  415. def getfile(object):
  416.     '''Work out which source or compiled file an object was defined in.'''
  417.     if ismodule(object):
  418.         if hasattr(object, '__file__'):
  419.             return object.__file__
  420.         raise TypeError('arg is a built-in module')
  421.     ismodule(object)
  422.     if isclass(object):
  423.         object = sys.modules.get(object.__module__)
  424.         if hasattr(object, '__file__'):
  425.             return object.__file__
  426.         raise TypeError('arg is a built-in class')
  427.     isclass(object)
  428.     if ismethod(object):
  429.         object = object.im_func
  430.     
  431.     if isfunction(object):
  432.         object = object.func_code
  433.     
  434.     if istraceback(object):
  435.         object = object.tb_frame
  436.     
  437.     if isframe(object):
  438.         object = object.f_code
  439.     
  440.     if iscode(object):
  441.         return object.co_filename
  442.     raise TypeError('arg is not a module, class, method, function, traceback, frame, or code object')
  443.  
  444. ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
  445.  
  446. def getmoduleinfo(path):
  447.     '''Get the module name, suffix, mode, and module type for a given file.'''
  448.     filename = os.path.basename(path)
  449.     suffixes = map((lambda info: (-len(info[0]), info[0], info[1], info[2])), imp.get_suffixes())
  450.     suffixes.sort()
  451.     for neglen, suffix, mode, mtype in suffixes:
  452.         if filename[neglen:] == suffix:
  453.             return ModuleInfo(filename[:neglen], suffix, mode, mtype)
  454.     
  455.  
  456.  
  457. def getmodulename(path):
  458.     '''Return the module name for a given file, or None.'''
  459.     info = getmoduleinfo(path)
  460.     if info:
  461.         return info[0]
  462.  
  463.  
  464. def getsourcefile(object):
  465.     '''Return the Python source file an object was defined in, if it exists.'''
  466.     filename = getfile(object)
  467.     if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
  468.         filename = filename[:-4] + '.py'
  469.     
  470.     for suffix, mode, kind in imp.get_suffixes():
  471.         if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
  472.             return None
  473.     
  474.     if os.path.exists(filename):
  475.         return filename
  476.     if hasattr(getmodule(object, filename), '__loader__'):
  477.         return filename
  478.  
  479.  
  480. def getabsfile(object, _filename = None):
  481.     '''Return an absolute path to the source or compiled file for an object.
  482.  
  483.     The idea is for each object to have a unique origin, so this routine
  484.     normalizes the result as much as possible.'''
  485.     if _filename is None:
  486.         if not getsourcefile(object):
  487.             pass
  488.         _filename = getfile(object)
  489.     
  490.     return os.path.normcase(os.path.abspath(_filename))
  491.  
  492. modulesbyfile = { }
  493. _filesbymodname = { }
  494.  
  495. def getmodule(object, _filename = None):
  496.     '''Return the module an object was defined in, or None if not found.'''
  497.     if ismodule(object):
  498.         return object
  499.     if hasattr(object, '__module__'):
  500.         return sys.modules.get(object.__module__)
  501.     if _filename is not None and _filename in modulesbyfile:
  502.         return sys.modules.get(modulesbyfile[_filename])
  503.     
  504.     try:
  505.         file = getabsfile(object, _filename)
  506.     except TypeError:
  507.         _filename in modulesbyfile
  508.         _filename in modulesbyfile
  509.         hasattr(object, '__module__')
  510.         return None
  511.         ismodule(object)
  512.  
  513.     if file in modulesbyfile:
  514.         return sys.modules.get(modulesbyfile[file])
  515.     for modname, module in sys.modules.items():
  516.         if ismodule(module) and hasattr(module, '__file__'):
  517.             f = module.__file__
  518.             _filesbymodname[modname] = f
  519.             f = getabsfile(module)
  520.             continue
  521.         modulesbyfile[f] = modulesbyfile[os.path.realpath(f)] = module.__name__
  522.     
  523.     if file in modulesbyfile:
  524.         return sys.modules.get(modulesbyfile[file])
  525.     main = sys.modules['__main__']
  526.     if not hasattr(object, '__name__'):
  527.         return None
  528.     builtin = sys.modules['__builtin__']
  529.  
  530.  
  531. def findsource(object):
  532.     '''Return the entire source file and starting line number for an object.
  533.  
  534.     The argument may be a module, class, method, function, traceback, frame,
  535.     or code object.  The source code is returned as a list of all the lines
  536.     in the file and the line number indexes a line in that list.  An IOError
  537.     is raised if the source code cannot be retrieved.'''
  538.     if not getsourcefile(object):
  539.         pass
  540.     file = getfile(object)
  541.     module = getmodule(object, file)
  542.     if module:
  543.         lines = linecache.getlines(file, module.__dict__)
  544.     else:
  545.         lines = linecache.getlines(file)
  546.     if not lines:
  547.         raise IOError('could not get source code')
  548.     lines
  549.     if ismodule(object):
  550.         return (lines, 0)
  551.     if isclass(object):
  552.         name = object.__name__
  553.         pat = re.compile('^(\\s*)class\\s*' + name + '\\b')
  554.         candidates = []
  555.         for i in range(len(lines)):
  556.             match = pat.match(lines[i])
  557.             if match:
  558.                 if lines[i][0] == 'c':
  559.                     return (lines, i)
  560.                 candidates.append((match.group(1), i))
  561.                 continue
  562.             lines[i][0] == 'c'
  563.         
  564.         if candidates:
  565.             candidates.sort()
  566.             return (lines, candidates[0][1])
  567.         raise IOError('could not find class definition')
  568.     isclass(object)
  569.     if ismethod(object):
  570.         object = object.im_func
  571.     
  572.     if isfunction(object):
  573.         object = object.func_code
  574.     
  575.     if istraceback(object):
  576.         object = object.tb_frame
  577.     
  578.     if isframe(object):
  579.         object = object.f_code
  580.     
  581.     if iscode(object):
  582.         if not hasattr(object, 'co_firstlineno'):
  583.             raise IOError('could not find function definition')
  584.         hasattr(object, 'co_firstlineno')
  585.         lnum = object.co_firstlineno - 1
  586.         pat = re.compile('^(\\s*def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)')
  587.         while lnum > 0:
  588.             if pat.match(lines[lnum]):
  589.                 break
  590.             
  591.             lnum = lnum - 1
  592.         return (lines, lnum)
  593.     raise IOError('could not find code object')
  594.  
  595.  
  596. def getcomments(object):
  597.     """Get lines of comments immediately preceding an object's source code.
  598.  
  599.     Returns None when source can't be found.
  600.     """
  601.     
  602.     try:
  603.         (lines, lnum) = findsource(object)
  604.     except (IOError, TypeError):
  605.         return None
  606.  
  607.     if ismodule(object):
  608.         start = 0
  609.         if lines and lines[0][:2] == '#!':
  610.             start = 1
  611.         
  612.         while start < len(lines) and string.strip(lines[start]) in ('', '#'):
  613.             start = start + 1
  614.         if start < len(lines) and lines[start][:1] == '#':
  615.             comments = []
  616.             end = start
  617.             while end < len(lines) and lines[end][:1] == '#':
  618.                 comments.append(string.expandtabs(lines[end]))
  619.                 end = end + 1
  620.             return string.join(comments, '')
  621.     elif lnum > 0:
  622.         indent = indentsize(lines[lnum])
  623.         end = lnum - 1
  624.         if end >= 0 and string.lstrip(lines[end])[:1] == '#' and indentsize(lines[end]) == indent:
  625.             comments = [
  626.                 string.lstrip(string.expandtabs(lines[end]))]
  627.             if end > 0:
  628.                 end = end - 1
  629.                 comment = string.lstrip(string.expandtabs(lines[end]))
  630.                 while comment[:1] == '#' and indentsize(lines[end]) == indent:
  631.                     comments[:0] = [
  632.                         comment]
  633.                     end = end - 1
  634.                     if end < 0:
  635.                         break
  636.                     
  637.                     comment = string.lstrip(string.expandtabs(lines[end]))
  638.             
  639.             while comments and string.strip(comments[0]) == '#':
  640.                 comments[:1] = []
  641.             while comments and string.strip(comments[-1]) == '#':
  642.                 comments[-1:] = []
  643.             return string.join(comments, '')
  644.     
  645.  
  646.  
  647. class EndOfBlock(Exception):
  648.     pass
  649.  
  650.  
  651. class BlockFinder:
  652.     '''Provide a tokeneater() method to detect the end of a code block.'''
  653.     
  654.     def __init__(self):
  655.         self.indent = 0
  656.         self.islambda = False
  657.         self.started = False
  658.         self.passline = False
  659.         self.last = 1
  660.  
  661.     
  662.     def tokeneater(self, type, token, srow_scol, erow_ecol, line):
  663.         (srow, scol) = srow_scol
  664.         (erow, ecol) = erow_ecol
  665.         if not self.started:
  666.             if token in ('def', 'class', 'lambda'):
  667.                 if token == 'lambda':
  668.                     self.islambda = True
  669.                 
  670.                 self.started = True
  671.             
  672.             self.passline = True
  673.         elif type == tokenize.NEWLINE:
  674.             self.passline = False
  675.             self.last = srow
  676.             if self.islambda:
  677.                 raise EndOfBlock
  678.             self.islambda
  679.         elif self.passline:
  680.             pass
  681.         elif type == tokenize.INDENT:
  682.             self.indent = self.indent + 1
  683.             self.passline = True
  684.         elif type == tokenize.DEDENT:
  685.             self.indent = self.indent - 1
  686.             if self.indent <= 0:
  687.                 raise EndOfBlock
  688.             self.indent <= 0
  689.         elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
  690.             raise EndOfBlock
  691.         
  692.  
  693.  
  694.  
  695. def getblock(lines):
  696.     '''Extract the block of code at the top of the given list of lines.'''
  697.     blockfinder = BlockFinder()
  698.     
  699.     try:
  700.         tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
  701.     except (EndOfBlock, IndentationError):
  702.         pass
  703.  
  704.     return lines[:blockfinder.last]
  705.  
  706.  
  707. def getsourcelines(object):
  708.     '''Return a list of source lines and starting line number for an object.
  709.  
  710.     The argument may be a module, class, method, function, traceback, frame,
  711.     or code object.  The source code is returned as a list of the lines
  712.     corresponding to the object and the line number indicates where in the
  713.     original source file the first line of code was found.  An IOError is
  714.     raised if the source code cannot be retrieved.'''
  715.     (lines, lnum) = findsource(object)
  716.     if ismodule(object):
  717.         return (lines, 0)
  718.     return (getblock(lines[lnum:]), lnum + 1)
  719.  
  720.  
  721. def getsource(object):
  722.     '''Return the text of the source code for an object.
  723.  
  724.     The argument may be a module, class, method, function, traceback, frame,
  725.     or code object.  The source code is returned as a single string.  An
  726.     IOError is raised if the source code cannot be retrieved.'''
  727.     (lines, lnum) = getsourcelines(object)
  728.     return string.join(lines, '')
  729.  
  730.  
  731. def walktree(classes, children, parent):
  732.     '''Recursive helper function for getclasstree().'''
  733.     results = []
  734.     classes.sort(key = attrgetter('__module__', '__name__'))
  735.     for c in classes:
  736.         results.append((c, c.__bases__))
  737.         if c in children:
  738.             results.append(walktree(children[c], children, c))
  739.             continue
  740.     
  741.     return results
  742.  
  743.  
  744. def getclasstree(classes, unique = 0):
  745.     """Arrange the given list of classes into a hierarchy of nested lists.
  746.  
  747.     Where a nested list appears, it contains classes derived from the class
  748.     whose entry immediately precedes the list.  Each entry is a 2-tuple
  749.     containing a class and a tuple of its base classes.  If the 'unique'
  750.     argument is true, exactly one entry appears in the returned structure
  751.     for each class in the given list.  Otherwise, classes using multiple
  752.     inheritance and their descendants will appear multiple times."""
  753.     children = { }
  754.     roots = []
  755.     for c in classes:
  756.         if c.__bases__:
  757.             for parent in c.__bases__:
  758.                 if parent not in children:
  759.                     children[parent] = []
  760.                 
  761.                 children[parent].append(c)
  762.                 if unique and parent in classes:
  763.                     break
  764.                     continue
  765.             
  766.         if c not in roots:
  767.             roots.append(c)
  768.             continue
  769.     
  770.     for parent in children:
  771.         if parent not in classes:
  772.             roots.append(parent)
  773.             continue
  774.     
  775.     return walktree(roots, children, None)
  776.  
  777. Arguments = namedtuple('Arguments', 'args varargs keywords')
  778.  
  779. def getargs(co):
  780.     """Get information about the arguments accepted by a code object.
  781.  
  782.     Three things are returned: (args, varargs, varkw), where 'args' is
  783.     a list of argument names (possibly containing nested lists), and
  784.     'varargs' and 'varkw' are the names of the * and ** arguments or None."""
  785.     if not iscode(co):
  786.         raise TypeError('arg is not a code object')
  787.     iscode(co)
  788.     nargs = co.co_argcount
  789.     names = co.co_varnames
  790.     args = list(names[:nargs])
  791.     step = 0
  792.     for i in range(nargs):
  793.         if args[i][:1] in ('', '.'):
  794.             stack = []
  795.             remain = []
  796.             count = []
  797.             while step < len(co.co_code):
  798.                 op = ord(co.co_code[step])
  799.                 step = step + 1
  800.                 if op >= dis.HAVE_ARGUMENT:
  801.                     opname = dis.opname[op]
  802.                     value = ord(co.co_code[step]) + ord(co.co_code[step + 1]) * 256
  803.                     step = step + 2
  804.                     if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
  805.                         remain.append(value)
  806.                         count.append(value)
  807.                     elif opname == 'STORE_FAST':
  808.                         stack.append(names[value])
  809.                         if not remain:
  810.                             stack[0] = [
  811.                                 stack[0]]
  812.                             break
  813.                         else:
  814.                             remain[-1] = remain[-1] - 1
  815.                             while remain[-1] == 0:
  816.                                 remain.pop()
  817.                                 size = count.pop()
  818.                                 stack[-size:] = [
  819.                                     stack[-size:]]
  820.                                 if not remain:
  821.                                     break
  822.                                 
  823.                                 remain[-1] = remain[-1] - 1
  824.                             if not remain:
  825.                                 break
  826.                             
  827.                     
  828.                 opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE')
  829.             args[i] = stack[0]
  830.             continue
  831.     
  832.     varargs = None
  833.     if co.co_flags & CO_VARARGS:
  834.         varargs = co.co_varnames[nargs]
  835.         nargs = nargs + 1
  836.     
  837.     varkw = None
  838.     if co.co_flags & CO_VARKEYWORDS:
  839.         varkw = co.co_varnames[nargs]
  840.     
  841.     return Arguments(args, varargs, varkw)
  842.  
  843. ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
  844.  
  845. def getargspec(func):
  846.     """Get the names and default values of a function's arguments.
  847.  
  848.     A tuple of four things is returned: (args, varargs, varkw, defaults).
  849.     'args' is a list of the argument names (it may contain nested lists).
  850.     'varargs' and 'varkw' are the names of the * and ** arguments or None.
  851.     'defaults' is an n-tuple of the default values of the last n arguments.
  852.     """
  853.     if ismethod(func):
  854.         func = func.im_func
  855.     
  856.     if not isfunction(func):
  857.         raise TypeError('arg is not a Python function')
  858.     isfunction(func)
  859.     (args, varargs, varkw) = getargs(func.func_code)
  860.     return ArgSpec(args, varargs, varkw, func.func_defaults)
  861.  
  862. ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
  863.  
  864. def getargvalues(frame):
  865.     """Get information about arguments passed into a particular frame.
  866.  
  867.     A tuple of four things is returned: (args, varargs, varkw, locals).
  868.     'args' is a list of the argument names (it may contain nested lists).
  869.     'varargs' and 'varkw' are the names of the * and ** arguments or None.
  870.     'locals' is the locals dictionary of the given frame."""
  871.     (args, varargs, varkw) = getargs(frame.f_code)
  872.     return ArgInfo(args, varargs, varkw, frame.f_locals)
  873.  
  874.  
  875. def joinseq(seq):
  876.     if len(seq) == 1:
  877.         return '(' + seq[0] + ',)'
  878.     return '(' + string.join(seq, ', ') + ')'
  879.  
  880.  
  881. def strseq(object, convert, join = joinseq):
  882.     '''Recursively walk a sequence, stringifying each element.'''
  883.     if type(object) in (list, tuple):
  884.         return join(map((lambda o, c = convert, j = join: strseq(o, c, j)), object))
  885.     return convert(object)
  886.  
  887.  
  888. def formatargspec(args, varargs = None, varkw = None, defaults = None, formatarg = str, formatvarargs = (lambda name: '*' + name), formatvarkw = (lambda name: '**' + name), formatvalue = (lambda value: '=' + repr(value)), join = joinseq):
  889.     '''Format an argument spec from the 4 values returned by getargspec.
  890.  
  891.     The first four arguments are (args, varargs, varkw, defaults).  The
  892.     other four arguments are the corresponding optional formatting functions
  893.     that are called to turn names and values into strings.  The ninth
  894.     argument is an optional function to format the sequence of arguments.'''
  895.     specs = []
  896.     if defaults:
  897.         firstdefault = len(args) - len(defaults)
  898.     
  899.     for i in range(len(args)):
  900.         spec = strseq(args[i], formatarg, join)
  901.         if defaults and i >= firstdefault:
  902.             spec = spec + formatvalue(defaults[i - firstdefault])
  903.         
  904.         specs.append(spec)
  905.     
  906.     if varargs is not None:
  907.         specs.append(formatvarargs(varargs))
  908.     
  909.     if varkw is not None:
  910.         specs.append(formatvarkw(varkw))
  911.     
  912.     return '(' + string.join(specs, ', ') + ')'
  913.  
  914.  
  915. def formatargvalues(args, varargs, varkw, locals, formatarg = str, formatvarargs = (lambda name: '*' + name), formatvarkw = (lambda name: '**' + name), formatvalue = (lambda value: '=' + repr(value)), join = joinseq):
  916.     '''Format an argument spec from the 4 values returned by getargvalues.
  917.  
  918.     The first four arguments are (args, varargs, varkw, locals).  The
  919.     next four arguments are the corresponding optional formatting functions
  920.     that are called to turn names and values into strings.  The ninth
  921.     argument is an optional function to format the sequence of arguments.'''
  922.     
  923.     def convert(name, locals = locals, formatarg = formatarg, formatvalue = formatvalue):
  924.         return formatarg(name) + formatvalue(locals[name])
  925.  
  926.     specs = []
  927.     for i in range(len(args)):
  928.         specs.append(strseq(args[i], convert, join))
  929.     
  930.     if varargs:
  931.         specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  932.     
  933.     if varkw:
  934.         specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  935.     
  936.     return '(' + string.join(specs, ', ') + ')'
  937.  
  938. Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
  939.  
  940. def getframeinfo(frame, context = 1):
  941.     '''Get information about a frame or traceback object.
  942.  
  943.     A tuple of five things is returned: the filename, the line number of
  944.     the current line, the function name, a list of lines of context from
  945.     the source code, and the index of the current line within that list.
  946.     The optional second argument specifies the number of lines of context
  947.     to return, which are centered around the current line.'''
  948.     if istraceback(frame):
  949.         lineno = frame.tb_lineno
  950.         frame = frame.tb_frame
  951.     else:
  952.         lineno = frame.f_lineno
  953.     if not isframe(frame):
  954.         raise TypeError('arg is not a frame or traceback object')
  955.     isframe(frame)
  956.     if not getsourcefile(frame):
  957.         pass
  958.     filename = getfile(frame)
  959.     if context > 0:
  960.         start = lineno - 1 - context // 2
  961.         
  962.         try:
  963.             (lines, lnum) = findsource(frame)
  964.         except IOError:
  965.             lines = None
  966.             index = None
  967.  
  968.         start = max(start, 1)
  969.         start = max(0, min(start, len(lines) - context))
  970.         lines = lines[start:start + context]
  971.         index = lineno - 1 - start
  972.     else:
  973.         lines = None
  974.         index = None
  975.     return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
  976.  
  977.  
  978. def getlineno(frame):
  979.     '''Get the line number from a frame object, allowing for optimization.'''
  980.     return frame.f_lineno
  981.  
  982.  
  983. def getouterframes(frame, context = 1):
  984.     '''Get a list of records for a frame and all higher (calling) frames.
  985.  
  986.     Each record contains a frame object, filename, line number, function
  987.     name, a list of lines of context, and index within the context.'''
  988.     framelist = []
  989.     while frame:
  990.         framelist.append((frame,) + getframeinfo(frame, context))
  991.         frame = frame.f_back
  992.     return framelist
  993.  
  994.  
  995. def getinnerframes(tb, context = 1):
  996.     """Get a list of records for a traceback's frame and all lower frames.
  997.  
  998.     Each record contains a frame object, filename, line number, function
  999.     name, a list of lines of context, and index within the context."""
  1000.     framelist = []
  1001.     while tb:
  1002.         framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  1003.         tb = tb.tb_next
  1004.     return framelist
  1005.  
  1006. currentframe = sys._getframe
  1007.  
  1008. def stack(context = 1):
  1009.     """Return a list of records for the stack above the caller's frame."""
  1010.     return getouterframes(sys._getframe(1), context)
  1011.  
  1012.  
  1013. def trace(context = 1):
  1014.     '''Return a list of records for the stack below the current exception.'''
  1015.     return getinnerframes(sys.exc_info()[2], context)
  1016.  
  1017.